/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.smarttmt.idu.web.model;

import com.smarttmt.idu.web.behavior.Preloadable;
import com.smarttmt.idu.web.persistence.controller.UsuacontJpaController;
import com.smarttmt.idu.web.utilities.FacesUtils;
import com.smarttmt.idu.web.utilities.MessagesApp;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.faces.application.ConfigurableNavigationHandler;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.http.HttpSession;
import javax.transaction.UserTransaction;

/**
 *
 * @author Nicolás Rubén Caballero Ortega (helaman58@gmail.com)
 */
@Named(value = "userLoginBean")
@SessionScoped
public class UserLogin implements Serializable, Preloadable {

    private String username;
    private String password;
    private boolean authenticated;
    private String todayStr;
    private String fromURL;
    private String destinyURL;
    @PersistenceUnit(unitName = "smarttmtiduappPU")
    private EntityManagerFactory emf;
    @Resource
    private UserTransaction utx;
    private UsuacontJpaController usuacontJpaController;

    /**
     * Creates a new instance of UserLogin
     */
    public UserLogin() {
    }

    @PostConstruct
    public void initpostConstructorUserLogin() {
        usuacontJpaController = new UsuacontJpaController(utx, emf);
    }

    public void resetData() {
        this.username = null;
        this.password = null;
        this.authenticated = false;
        this.todayStr = null;
    }

    @Override
    public void preload(Map<String, Object> parameters) throws Exception {
        resetData();
        fromURL = (String) parameters.get("fromURL");
        System.out.println(fromURL);
        destinyURL = (String) parameters.get("destinyURL");
        System.out.println(destinyURL);
    }

    public void validateSession(ComponentSystemEvent event) {

        FacesContext fc = FacesContext.getCurrentInstance();

        if (!authenticated) {

            ConfigurableNavigationHandler nav
                    = (ConfigurableNavigationHandler) fc.getApplication().getNavigationHandler();

            nav.performNavigation("userLogin");
        }
    }

    public String closeSession() {
        resetData();
        System.out.println("Cerrando Sesion");
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        session.invalidate();
        return "index";
    }

    public String authenticate() throws Exception {
        authenticated = false;

        if (usuacontJpaController.existUserByNomb(username) && usuacontJpaController.validateUserSignIn(username, password)) {
            authenticated = true;
        } else {
            FacesContext.getCurrentInstance().addMessage("msgsLogin", new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    FacesUtils.getMessageFromBundle(MessagesApp.FILES_MESSAGES.MESSAGES_INTERNAL, "page.userLogin.errorAuthSumary"),
                    FacesUtils.getMessageFromBundle(MessagesApp.FILES_MESSAGES.MESSAGES_INTERNAL, "page.userLogin.errorDetailSumary")));
            return null;
        }
        /*        
         if (usuacontJpaController.needToCompleteAditionalInfo(username)) {
         FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Complete su informacion de usuario", "Esta información es necesaria."));
         Preloadable bean = (Preloadable) FacesUtils.getManagedBean("aditionalInformationBean");
         Map<String, Object> parameters = new HashMap<>();
         parameters.put("username", username);
         bean.preload(parameters);
         return "aditionalInformation";
         }
         */
        if (isAuthenticated()) {
            try {
                //Preloadable bean = (Preloadable) FacesUtils.getManagedBean("validatePINBean");
                //bean.preload(null);
                //return "validatePIN";
                if (destinyURL != null) {
                    Preloadable bean = (Preloadable) FacesUtils.getManagedBean(destinyURL + "Bean");
                    bean.preload(null);
                    return destinyURL;
                } else {
                    return "/faces/site/index.xhtml";
                }
            } catch (Exception e) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "NO ha sido posible iniciar sesion", "Comunicarse con soporte..."));
                return null;
            }

        } else {
            return null;
        }

    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isAuthenticated() {
        return authenticated;
    }

    public void setAuthenticated(boolean authenticated) {
        this.authenticated = authenticated;
    }

    public String getTodayStr() {
        return todayStr;
    }

    public void setTodayStr(String todayStr) {
        this.todayStr = todayStr;
    }

    public EntityManagerFactory getEmf() {
        return emf;
    }

    public void setEmf(EntityManagerFactory emf) {
        this.emf = emf;
    }

    public UserTransaction getUtx() {
        return utx;
    }

    public void setUtx(UserTransaction utx) {
        this.utx = utx;
    }

    public UsuacontJpaController getUsuacontJpaController() {
        return usuacontJpaController;
    }

    public void setUsuacontJpaController(UsuacontJpaController usuacontJpaController) {
        this.usuacontJpaController = usuacontJpaController;
    }

    public String getFromURL() {
        return fromURL;
    }

    public void setFromURL(String fromURL) {
        this.fromURL = fromURL;
    }

    public String getDestinyURL() {
        return destinyURL;
    }

    public void setDestinyURL(String destinyURL) {
        this.destinyURL = destinyURL;
    }

}
